import java.sql.Connection
import java.sql.DriverManager
import org.dbunit.database.DatabaseConnection
import org.dbunit.dataset.xml.FlatXmlDataSet
import org.dbunit.dataset.CompositeDataSet
import org.dbunit.dataset.IDataSet
import org.dbunit.operation.DatabaseOperation

/*
*   Copyright 2008 Marcos Silva Pereira
*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
*/
 
eventStartIntegrationTests = {
    println "Loading dataset for DBUnit..."
    try {
        DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet)
        println "Commiting inserts for DBUnit"
    } catch(Exception ex) {
        ex.printStackTrace()
    }
}

eventFinishIntegrationTests = {
    println "Unloading dataset from DBUnit..."
    try {
        DatabaseOperation.DELETE_ALL.execute connection, dataSet
    } catch (Exception ex) {
        ex.printStackTrace()
    }
}

def getConnection() {
    
    URL url = new File("${basedir}/grails-app/conf/DataSource.groovy").toURL()
    def config = new ConfigSlurper('test').parse(url)

    def username    = config.dataSource.username
    def password    = config.dataSource.password
    def databaseUrl = config.dataSource.url
    def driver      = config.dataSource.driverClassName

    Class.forName(driver)

    println """
Connection Properties:
 url      = ${databaseUrl}
 username = ${username}
 password = ${password}
 driver   = ${driver} 
"""

    Connection connection = DriverManager.getConnection(databaseUrl, username, password)
    connection.setAutoCommit true
    println "Connection opened: $connection"
    return new DatabaseConnection(connection)
    
}

def getDataSet() {
    
    File dataSetDirectory = new File("${basedir}/test/dataset/")
    def datasets = []
    dataSetDirectory.eachFileRecurse {
        if(!(it =~ /svn/)) {
            println "Adding dataset [${it}]"
            datasets << it
        }
    }

    return new CompositeDataSet(datasets.sort { it }.collect { new FlatXmlDataSet(it) } as IDataSet[])
    
}
